// miniprogram/pages/admin/team/new/newUser.js
const app = getApp();
const util = require("../../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    jobList: ['摄影师', '客服', '后期', '化妆', '管理员'],
    rules: {
      name: 'require',
      phone: 'require',

    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.options = options
    // console.log(options);
    const that = this;
    var studio;

    app.login(user => {
      console.log('user', user)
      this.setData({
        user
      });
      // 无效参数，或者当前用户正在本工作室，直接跳转首页
      if (!options.studioid || options.studioid == user.studioid) {
        wx.reLaunch({
          url: '/pages/admin/index/index',
        });
        return;
      }
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'get',
          table: 'studio',
          where: {
            _id: options.studioid
          }
        },
        success: res => {
          if (res.result.data.length == 0) {
            // 工作室不存在，直接转到首页
            wx.showModal({
              content: '工作室不存在',
              showCancel: false,
              success: r => {
                wx.reLaunch({
                  url: '/pages/admin/index/index',
                });
              }
            });
            return;
          }
          studio = res.result.data[0];
          that.setData({
            studio: studio
          });
          // 检查当前用户与工作室的关系
          // 用户是本工作室创始人，临时切换到本工作室，然后跳转到首页  
          // 注意：这种用户下次打开小程序，还是会切换到上次手动切换的工作室
          if (user.openid == studio._openid) {
            app.globalData.user.studioid = studio._id;
            app.globalData.user.studio = studio;
            wx.reLaunch({
              url: '/pages/admin/index/index',
            });
            return;
          }
          // 用户已经是本工作室成员，且当前工作室对应，转到首页
          if (user.studioid == options.studioid) {
            wx.showModal({
              content: '您已经是本工作室成员',
              showCancel: false,
              success: r => {
                wx.reLaunch({
                  url: '/pages/admin/index/index',
                });
              }
            });
            return;
          }

          wx.cloud.callFunction({
            name: 'crud',
            data: {
              op: 'get',
              table: 'team',
              where: {
                studioid: options.studioid,
                openid: user.openid
              }
            },
            success: rr => {
              if (rr.result.data.length > 0) {
                let team_user = rr.result.data[0];
                if (team_user.status == 1) {
                  // 切换至本工作室
                  app.globalData.user.studioid = studio._id;
                  app.globalData.user.studio = studio;
                  wx.cloud.callFunction({
                    name: 'crud',
                    data: {
                      op: 'update',
                      table: 'user',
                      data: {
                        _id: user.openid,
                        studioid: studio._id
                      }
                    }
                  })
                  wx.showModal({
                    content: '您已经是本工作室成员',
                    showCancel: false,
                    success: r => {
                      wx.reLaunch({
                        url: '/pages/admin/index/index',
                      });
                    }
                  });
                  return;
                } else {
                  that.setData({
                    user: team_user
                  })
                }
                // 其它三种情况：
                //    未授权、已授权未申请：填写申请
                //    申请未通过  显示尚未审批
              } else {
                // that.setData({
                //   user: {
                //     openid: user.openid,
                //     studioid: studio._id,
                //     job: this.data.jobList[0],
                //     sales: 0,
                //     updatetime: util.formatTime(new Date())
                //   }
                // });
              }
            }
          });
        }
      })
    });

  },


  getUserInfo(e) {
    let that = this
    let user = this.data.user;
    wx.getUserProfile({
      desc: '业务需要',
      success: res => {
        console.log(res)
        let userinfo = res.userInfo
        //


        console.log("授权用户信息", userinfo)
        if (!user) {
          wx.showModal({
            content: '需要授权才能继续',
            showCancel: false
          })
          return;
        } else {

          user.nickName = userinfo.nickName;
          user.avatarUrl = userinfo.avatarUrl;
          user.country = userinfo.country;
          user.province = userinfo.province;
          user.gender = userinfo.gender;
          user.city = userinfo.city;

          if (!user._id) {
            user._id = user.openid;
            wx.cloud.callFunction({
              name: 'crud',
              data: {
                table: 'user',
                op: 'add',
                data: user,
              },
              success: res => {
                console.log('新增用户')
                that.onLoad(that.options)

              }
            })
          }
        }
      }
    })
  },
  getPhoneNumber: function (e) {
    let cloudID = e.detail.cloudID //开放数据ID
    let user = this.data.user
    if (cloudID) {

      wx.cloud.callFunction({
        name: 'getPhone',
        data: {
          cloudID: cloudID
        }
      }).then(res => {
        this.setData({
          'user.phone': res.result.list[0].data.phoneNumber
        })


      })

    } else {
      this.setData({
        modalname: 'shouquan'
      })

    }
  },
  apply: function (e) {
    console.log(e)
    //  return;
    let checkResult = util.checkForm(e.detail.value, this.data.rules);
    console.log(checkResult)
    this.setData({
      errinfo: checkResult
    })
    if (Object.keys(checkResult).length != 0) {
      return;
    }



    this.setData({
      'user.status': 99
    });
    let team_user = {}

    team_user.studioid = this.data.studio._id;
    team_user.avatarUrl = this.data.user.avatarUrl;
    team_user.nickName = this.data.user.nickName;
    team_user.openid = this.data.user.openid
    team_user.job = this.data.jobList[0]
    team_user.name = e.detail.value.name;
    team_user.phone = e.detail.value.phone
    team_user.sales = 0
    team_user.status = 99;



    this.submitData(team_user);
  },
  /**
   * 保存数据
   */
  submitData: function (team_user) {
    console.log('提交数据', team_user)

    wx.showLoading({
      title: '正在提交数据'
    });



    let msg = {
      _openid: this.data.studio._openid,
      templateId: '6Yl15FvAIoRqTCjWYrf7vH1NcnPRzRFNBFiosr-BxyU',
      page: 'pages/admin/team/team',
      data: {
        thing1: {
          value: team_user.name, //姓名
        },
        phone_number2: {
          value: team_user.phone, //电话
        },
        time3: {
          value: util.cnformatTime(new Date()), //时间
        },

      }
    }
    console.log(msg)
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        table: 'team',
        op: 'update',
        data: team_user,
        msg
      },
      success: res => {
        wx.hideLoading();
        if (res.result._id) {
          team_user._id = res.result._id;
        }

        wx.cloud.callFunction({
          name: 'crud',
          data: {
            table: 'user',
            op: 'update',
            data: {
              // _id: user.openid,
              // studioid: studio._id
              _id: team_user.openid,
              studioid: this.data.studio._id
            }
          },
          success: res => {
            console.log('更新用户')
            // that.onLoad(that.options)

          }
        })

        this.setData({
          user: team_user
        });

        app.relogin();

        console.debug("Update result", res.result);

      },
      fail: err => {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },
  requestSubscribeMessage() {
    const templateId = ['4aMenw5kqZCNYGZA3IvAIRrwun7oMIRPaPWx89IIuCs']
    wx.requestSubscribeMessage({
      tmplIds: templateId,
      success: (res2) => {
        if (res2[templateId] === 'accept') {
          console.log('msg', '允许')
        } else {
          wx.openSetting({
            success(res) {
              console.log(res.authSetting)
              // res.authSetting = {
              //   "scope.userInfo": true,
              //   "scope.userLocation": true
              // }
            }
          })
          console.log('msg', '不允许')
        }
      },
      fail: (err) => {
        console.log('msg', `失败（${JSON.stringify(err)}）`)
        wx.openSetting({
          success(res) {
            console.log(res.authSetting)
            // res.authSetting = {
            //   "scope.userInfo": true,
            //   "scope.userLocation": true
            // }
          }
        })
      },
      complete: (res) => {

      }
    })
  },
  switchChange: function (e) {
    // console.log(e.detail);
    if (e.target.id) {
      this.setData({
        [`user.${e.target.id}`]: this.data.jobList[e.detail.value]
      });
    } else {
      console.error("控件没有设置 id!")
    }
  },

  inputChange: function (e) {
    // console.log(e.detail);
    if (e.target.id) {
      this.setData({
        [`user.${e.target.id}`]: e.detail.value
      });
    } else {
      console.error("控件没有设置 id!")
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})